﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Windows.Forms;
using GameEditor.Common.Controls;
using GameEditor.Common;

namespace TaskSystemClient
{
    partial class CatalogTaskTreeView
    {
        class ExportContext
        {
            XmlTextWriter writer;
            Set<TreeListNode> ignoredNodes = new Set<TreeListNode>();
            bool outputHiddenItems = false;

            public bool OutputHiddenItems
            {
                get { return outputHiddenItems; }
                set { outputHiddenItems = value; }
            }
           
            

            public XmlTextWriter Writer
            {
                get { return writer; }
            }
            public Set<TreeListNode> IgnoredNodes
            {
                get { return ignoredNodes; }
            }
            public ExportContext(XmlTextWriter writer)
            {
                this.writer = writer;
            }
        }

        private void WriteNode(ExportContext context, TreeListNode node)
        {
            if (!context.OutputHiddenItems)
            {
                //do not serialize invisible node
                if (node.Visible == false)
                    return;
            }
            if (context.IgnoredNodes.Contains(node))
                return;
            context.IgnoredNodes.Add(node);

            CatalogTreeNodeData nodeData = node.Tag as CatalogTreeNodeData;

            string nodeName = null;
            if (nodeData.TaskData == null)
                nodeName = "node";
            else
                nodeName = "task";

            string state = "<null>", priority = "<null>", type = "<null>", tags = "<null>", users = "<null>";
            if (nodeData.TaskData != null)
            {
                state = (nodeData.TaskData.Task.State ?? "").ToLower();
                priority = (nodeData.TaskData.Task.Priority ?? "").ToLower();
                type = (nodeData.TaskData.Task.Type ?? "").ToLower();
                tags = (nodeData.TaskData.Task.Tags_ForDisplay ?? "").ToLower();
                users = (nodeData.TaskData.Task.Users_ForDisplay ?? "").ToLower();
            }
            XmlTextWriter writer = context.Writer;
            writer.WriteStartElement(nodeName);
            writer.WriteAttributeString("title", nodeData.TaskData==null?nodeData.TaskData.Task.Title : nodeData.Catalog);
            writer.WriteAttributeString("level", (node.Level + 1) + "");
            writer.WriteAttributeString("state", state);
            writer.WriteAttributeString("type", type);
            writer.WriteAttributeString("priority", priority);
            writer.WriteAttributeString("tags", tags);
            writer.WriteAttributeString("users", users);
            writer.WriteEndElement();

            //write child nodes
            foreach (TreeListNode n in node.Nodes)
            {
                WriteNode(context, n);
            }
        }//WriteNode
        /// <summary>
        /// 导出视图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnExportView(object sender, EventArgs e)
        {
            string filename;
            using (ExportDialog dialog = new ExportDialog())
            {
                if (dialog.ShowDialog() != DialogResult.OK)
                    return;
            }
            filename = LocalSettings.LastExportedFileName;
            
            

            using (FileStream stream = new FileStream(filename, FileMode.Create))
            {
                stream.SetLength(0);
                using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
                {
                    ExportContext context = new ExportContext(writer);

                    context.OutputHiddenItems = LocalSettings.ExportHiddenItems;

                    string styleName = LocalSettings.StyleName;

                    writer.Indentation = 4;
                    //writer.Settings.Indent = true;
                    writer.Formatting = Formatting.Indented;

                    writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");

                    string styleSheetName="";
                    if (LocalSettings.UseSharedTemplate)
                    {
                        styleSheetName=String.Format("type=\"text/xsl\" href=\"E:/work/work/trunk/client_output/SPMData/templates/{0}\"",styleName);
                        //writer.WriteProcessingInstruction("xml-stylesheet", );
                    }
                    else
                    {
                        styleSheetName=String.Format("type=\"text/xsl\" href=\"{0}\"",styleName);
                    }

                    writer.WriteProcessingInstruction("xml-stylesheet", styleSheetName);

                    writer.WriteStartElement("view");
                    writer.WriteAttributeString("name", ViewTitle);

                    //serialize nodes
                    foreach (TreeListNode node in treeList.Nodes)
                        WriteNode(context, node);


                    writer.WriteEndElement();
                }
            }

            if (!LocalSettings.UseSharedTemplate)
            {
                //复制相关图片，css以及xsl样式表
                var destFolder = Path.GetDirectoryName(filename);
                var srcFolder = "E:/work/work/trunk/client_output/SPMData/templates/";
                string[] fileNames =
                {
                    "mm_lodging1.css","node.gif","mm_spacer.gif","link.gif","task.gif"
                };
                foreach (var file in fileNames)
                {
                    string sourceFile = Path.Combine(srcFolder, file);
                    string destFile = Path.Combine(destFolder, file);
                    if (!File.Exists(destFile) && File.Exists(sourceFile))
                    {
                        File.Copy(sourceFile, destFile);
                    }
                }
                string styleName = LocalSettings.StyleName;
                var xslTemplate = Path.Combine(destFolder, styleName);
                var code = File.ReadAllText(Path.Combine(srcFolder, styleName), Encoding.UTF8);
                if (code.Contains("E:/work/work/trunk/client_output/SPMData/templates/"))
                {
                    code = code.Replace("E:/work/work/trunk/client_output/SPMData/templates/", "");
                    try
                    {
                        File.WriteAllText(xslTemplate, code, Encoding.UTF8);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            Dialogs.Information("导出成功！", "导出");
        }
    }
}
